package modbus

import (
	"dcs/db"
	"dcs/model"
	"fmt"
	"strings"
	"time"
)

func (c *Client) SyncMachineConfig() *model.Base_machine {

	req := MakeReadMachineConfigRequest()

	c.Conn.Write(req)

	buf := make([]byte, 1024)
	n, err := c.Conn.Read(buf)
	if err != nil {
		fmt.Println("read err:", err)
		return nil
	}

	fmt.Println(string(buf[0:n]))

	var raw_data []byte = Modbus_decode(buf, n)

	var raw_machine = model.Raw_machine_config{}
	current := time.Now().Format("2006-01-02 15:04:05")
	ip := strings.Split(c.Conn.RemoteAddr().String(), ":")[0]
	raw_machine.Machine_ip = ip
	raw_machine.Dtime = current
	raw_machine.Raw_data = raw_data

	db.GormDb.Create(&raw_machine)

	machine := raw_machine.Interpret()
	machine.Dtime = current

	var exists_machine model.Base_machine
	handler := db.GormDb.Table("base_machine").Where("machine_ip = ?", ip).Find(&exists_machine)
	// 从数据库中查找 指定 IP 的机台， 若已存在 则更新， 若不存在则创建
	if exists_machine.Tid == 0 {
		db.GormDb.Create(&machine)
	} else {
		handler.Update(&machine)
	}

	return &machine
}
